package com.bg.print.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bg.print.config.MinioConfig;
import com.bg.print.dao.FileDao;
import com.bg.print.entity.FileEntity;
import com.bg.print.service.FileService;
import com.bg.print.utils.PageUtils;
import com.bg.print.utils.Query;
import com.bg.print.utils.URLUtils;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




@Service("fileService")
public class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FileEntity> page = this.page(
                new Query<FileEntity>().getPage(params),
                new QueryWrapper<FileEntity>()
        );
        PageUtils pageUtils = new PageUtils(page);
        List<FileEntity> list = (List<FileEntity>) pageUtils.getList();
        list.forEach(fileEntity -> {
            fileEntity.setModel(URLUtils.addPath(fileEntity.getModel(),minioConfig.getWarnEndpoint()));
        });


        return pageUtils;
    }

    @Override
    public String getToken(String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Map<String, String> reqParams = new HashMap<String, String>();
        reqParams.put("response-content-type", "application/json");
        String product = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.PUT) //这里必须是PUT，如果是GET的话就是文件访问地址了。如果是POST上传会报错.
                        .bucket(minioConfig.getBucketName())
                        .object(fileName)
                        .expiry(minioConfig.getActiveTime())
                        .extraQueryParams(reqParams)
                        .build());
        log.warn("url: "+product);
        return product;
    }

}